package com.usian.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.usian.pojo.User;
import com.usian.service.UserService;
import com.usian.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/toUser")
    public String toUser(){
        return "addUser";
    }


    /**
     * 查询所有用户
     *
     * @param model
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model,HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        model.addAttribute("user",user);

        List<User> userList = userService.findList();
        model.addAttribute("userList" ,userList);
        return "index";
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @RequestMapping("/insertUser")
    public String insertUser(User user){

        logger.info("====保存controller"+user.getUserId());
        if(user.getUserId()==null){
            userService.insertUser(user);
        }else{
            userService.updateUser(user);
        }
        return "redirect:/user/findAll";
    }

    /**
     * 回显
     *
     * @param id
     * @return
     */
    @RequestMapping("/toUpdate")
    public ModelAndView toUpdate(Integer id){
        User user = userService.findById(id);
        ModelAndView model = new ModelAndView();
        model.addObject("user",user);
        model.setViewName("update");
        return model;
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteById")
    public String deleteById(Integer id){
        userService.deleteById(id);
        return "redirect:/user/findAll";
    }



}
